<script lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { h, ref } from 'vue';
import { deleteDepts, fetchGetDeptList, getFetchDeptUrl } from '@/service/api';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAuth } from '@/hooks/business/auth';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { DICT_TYPE, getDictObj } from '@/utils/dict';
import DeptSearch from './modules/org-search.vue';
import DeptOperateModal from './modules/org-operate-modal.vue';

const appStore = useAppStore();
const { hasAuth } = useAuth();

const wrapperRef = ref<HTMLElement | null>(null);

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetDeptList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    status: null,
    name: null
  },
  columns: () => [
    {
      type: 'selection'
    },
    {
      key: 'name',
      title: $t('page.manage.dept.name'),
      width: 200
    },
    {
      key: 'leader',
      title: $t('page.manage.dept.leader'),
      align: 'center',
      width: 90
    },
    {
      key: 'sort',
      title: $t('page.manage.dept.sort'),
      align: 'center',
      width: 90
    },
    {
      key: 'status',
      title: $t('page.manage.dept.status'),
      align: 'center',
      width: 180,
      render: row => {
        if (row.status === null) {
          return null;
        }
        const dictObj = getDictObj(DICT_TYPE.COMMON_STATUS, row.status);

        return <NTag type={dictObj?.colorType}>{dictObj?.label}</NTag>;
      }
    },
    {
      key: 'createTime',
      title: $t('page.manage.dept.createTime'),
      align: 'center',
      width: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 120,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:dept:update')}>
            <NButton type="primary" ghost size="small" onClick={() => edit(row.id)}>
              {{
                default: () => $t('common.edit'),
                icon: () => h(SvgIcon, { icon: 'ep:edit' })
              }}
            </NButton>
          </div>
          <div v-show={hasAuth('system:dept:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const {
  modelVisible,
  operateType,
  editingData,
  handleEdit,
  handleAdd,
  onDeleted,
  fetchDataUrl
  // closeDrawer
} = useTableOperate(data, getData);

async function handleDelete(id: number) {
  // request
  const { error } = await deleteDepts(id.toString());
  await onDeleted(error);
}

function edit(id: number) {
  fetchDataUrl.value = getFetchDeptUrl(id);
  handleEdit(id);
}
</script>
<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <DeptSearch
      v-if="hasAuth('system:dept:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />

    <NCard :title="$t('page.manage.dept.title')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :loading="loading"
          create-auth="system:dept:create"
          delete-auth="system:dept:delete"
          delete-show="false"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1088"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />

      <DeptOperateModal
        v-model:visible="modelVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>
<style scoped></style>
